package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.BankerInfoResponse;
import com.ytjj.qmyx.supplychain.common.model.response.BankerInfoResponseRpc;
import com.ytjj.qmyx.supplychain.mapper.BankerInfoMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerMessageMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerInfo;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RefreshScope
public class BankerInfoService {
    @Resource
    private BankerInfoMapper bankerInfoMapper;
    @Resource
    private BankerMessageMapper bankerMessageMapper;
    @Autowired
    private BankerService bankerService;
    @Value(value = "${history-off:true}")
    private boolean historyOff;

    public YxBankerInfo selectByBankerId(Integer bankerId) {
        Example example = new Example(YxBankerInfo.class);
        example.createCriteria().andEqualTo("bankerId", bankerId);
        YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(example);
        return bankerInfo;
    }

    public CommonResult checkStatus(BankerCheckStatusRequest request) {
        log.info("供应商主体审核参数:{}", request);
        YxBankerInfo bankerInfo = bankerInfoMapper.selectByPrimaryKey(request.getId());
        if (null == bankerInfo) {
            return CommonResult.failed("找不到对应的供应商资质信息");
        }
        bankerInfo.setStatus(request.getStatus());
        bankerInfo.setRejectReason(request.getMsg());
        int count = bankerInfoMapper.updateByPrimaryKey(bankerInfo);
        if (count > 0) {
            return CommonResult.success("审核成功");
        }
        return CommonResult.failed("审核失败");
    }

    public CommonResult release(BankerUpdateReleaseRequest request) {
        YxBankerInfo info = bankerInfoMapper.selectByPrimaryKey(request.getId());
        if (null == info) {
            return CommonResult.failed("找不到主体信息");
        }
        info.setReleased(request.getStatus());
        int count = bankerInfoMapper.updateByPrimaryKey(info);
        if (count > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed("释放失败");
    }

    public int insert(YxBankerInfo bankerInfo) {
        Integer bankerId = bankerService.getUserInfo().getId();
        if (bankerId.equals(bankerInfo.getBankerId())) {
            throw new ApiException("您已经填写过了");
        }
        bankerInfo.setBankerId(bankerId);
        bankerInfo.setCreateTime(new Date());
        int count = bankerInfoMapper.insertSelective(bankerInfo);

        return count;
    }

    public BankerInfoRequest selectById() {
        Integer bankerId = bankerService.getUserInfo().getId();
        YxBankerInfo bankerInfo = selectByBankerId(bankerId);
        BankerInfoRequest info = new BankerInfoRequest();
        if (bankerInfo != null) {
            BeanUtils.copyProperties(bankerInfo, info);
            // 商标注册证
            String spImgs = info.getRegisterCertificate();
            List<ReceImgRequest> receImg = new ArrayList<>();
            if (spImgs != null) {
                String[] array = spImgs.split(",");
                for (String img : array) {
                    ReceImgRequest format = new ReceImgRequest();
                    format.setUrl(img);
                    receImg.add(format);
                }
            }
            info.setReceImgs(receImg);

            // 品牌授权书
            String sqImgs = info.getBrandLicensing();
            List<LicenImgRequest> licenImg = new ArrayList<>();
            if (!StringUtils.isEmpty(sqImgs)) {
                String[] array = sqImgs.split(",");
                for (String img : array) {
                    LicenImgRequest format = new LicenImgRequest();
                    format.setUrl(img);
                    licenImg.add(format);
                }
            }
            info.setLicenImgs(licenImg);
        }else {
            YxBanker banker = bankerService.getUserInfo();
            boolean isOldInfo = false;// true-历史数据  false-新数据
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date upLineTimeDate = sdf.parse("2021-04-13 00:00:00");
                if (banker.getCreateTime().before(upLineTimeDate) && historyOff) {
                    isOldInfo = true;
                }
            } catch (Exception e) {
                log.error("时间转换异常：{}", e);
            }
            if (isOldInfo) {
                info = new BankerInfoRequest();
                info.setReleased(1);
            }
        }
        return info;
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateById(YxBankerInfo bankerInfo) {
        YxBanker userInfo = bankerService.getUserInfo();
        // 查询库里面有没有用户信息
        YxBankerInfo yxBankerInfo = selectByBankerId(userInfo.getId());
        if(StringUtils.isEmpty(bankerInfo.getOpeningLicenseImg())){
            throw new ApiException("银行开户许可证为必填项！");
        }
        if(yxBankerInfo == null) {
            YxBankerInfo bankerInfos = new YxBankerInfo();
            bankerInfos.setBankerId(userInfo.getId());
            bankerInfos.setBankHouse(bankerInfo.getBankHouse());
            bankerInfos.setCreditCardNumbers(bankerInfo.getCreditCardNumbers());
            bankerInfos.setBankerName(userInfo.getName());
            bankerInfos.setStatus(1);
            bankerInfos.setCreditCartPerson(bankerInfo.getCreditCartPerson());
            bankerInfos.setBrandLicensing(bankerInfo.getBrandLicensing());
            bankerInfos.setBusinessLicense(bankerInfo.getBusinessLicense());
            bankerInfos.setBusinessLicenseImg(bankerInfo.getBusinessLicenseImg());
            bankerInfos.setCertification(bankerInfo.getCertification());
            bankerInfos.setCompanyAddress(bankerInfo.getCompanyAddress());
            bankerInfos.setCompanyName(bankerInfo.getCompanyName());
            bankerInfos.setCompanyTel(bankerInfo.getCompanyTel());
            bankerInfos.setIdCard(bankerInfo.getIdCard());
            bankerInfos.setHostName(bankerInfo.getHostName());
            bankerInfos.setCardImgFront(bankerInfo.getCardImgFront());
            bankerInfos.setCardImgBehind(bankerInfo.getCardImgBehind());
            bankerInfos.setCreditCardNumbers(bankerInfo.getCreditCardNumbers());
            bankerInfos.setBankHouse(bankerInfo.getBankHouse());
            bankerInfos.setCreateTime(new Date());
            bankerInfos.setBankerType(bankerInfo.getBankerType());
            bankerInfos.setRegisterCertificate(bankerInfo.getRegisterCertificate());
            bankerInfos.setOpeningLicenseImg(bankerInfo.getOpeningLicenseImg());
            return bankerInfoMapper.insert(bankerInfos);
        }
        if (null == yxBankerInfo.getReleased() || yxBankerInfo.getReleased().equals(0)) {
            log.warn("===供应商主体：" + yxBankerInfo.getId() + "，暂未开发修改权限");
            throw new ApiException("暂未开发修改权限，请联系客户");
        }
        bankerInfo.setBankerId(userInfo.getId());
        bankerInfo.setStatus(1);
        bankerInfo.setUpdateTime(new Date());
        bankerInfo.setRejectReason("");
        return bankerInfoMapper.updateById(bankerInfo);
    }

    public CommonPage<BankerInfoResponseRpc> selectList(BankerInfoRequest bankerInfoRequest) {
        PageHelper.startPage(bankerInfoRequest.getPageNum(), bankerInfoRequest.getPageSize());
        List<BankerInfoResponseRpc> pageList = bankerInfoMapper.selectList(bankerInfoRequest);
        if(!CollectionUtils.isEmpty(pageList)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for(BankerInfoResponseRpc info : pageList){
                if (null == info.getForver() || 1 == info.getForver()) {
                    info.setBusinessLimit("长期");
                }else {
                    String startTime = "";
                    String endTime = "";
                    if (null != info.getBusinessLimitStart()) {
                        startTime = sdf.format(info.getBusinessLimitStart());
                    }
                    if (null != info.getBusinessLimitEnd()) {
                        endTime = sdf.format(info.getBusinessLimitEnd());
                    }
                    if (com.alibaba.excel.util.StringUtils.isEmpty(startTime) && com.alibaba.excel.util.StringUtils.isEmpty(endTime)) {
                        info.setBusinessLimit("");
                    }else {
                        info.setBusinessLimit(startTime + "至" + endTime);
                    }
                }
                // 商标注册证
                String cate = info.getRegisterCertificate();
                List<String> cateList = new ArrayList<>();
                if(cate != null) {
                    String[] array = cate.split(",");
                    for(int i = 0; i<array.length; i++) {
                        cateList.add(array[i]);
                    }
                }
                info.setCateLists(cateList);
                // 品牌授权书
                String licen = info.getBrandLicensing();
                List<String> licenList = new ArrayList<>();
                if(licen != null) {
                    String[] array = licen.split(",");
                    for(int i = 0; i<array.length; i++) {
                        licenList.add(array[i]);
                    }
                }
                info.setLicenLists(licenList);

                if (info.getStatus() != 3 ){
                    info.setRejectReason("");
                }
            }
        }
        return CommonPage.restPage(pageList);
    }

    public YxBankerInfo selectIdentity(Integer id) {
        return bankerInfoMapper.selectByPrimaryKey(id);
    }

    public Integer verifySuccess(Integer id, String adminName) {
        Integer count = bankerInfoMapper.verifySuccess(id, adminName);
        if (count > 0) {
            YxBankerInfo bankerInfo = bankerInfoMapper.selectByPrimaryKey(id);
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(bankerInfo.getBankerId());
            message.setBankerName(bankerInfo.getBankerName());
            message.setRemarks("您上传的商家信息："+bankerInfo.getBankerName()+" 已通过审核！");
            message.setStatus(0);
            message.setType(5);
            message.setCreateTime(new Date());
            bankerMessageMapper.insert(message);
        }
        return count;
    }

    public Integer verifyFail(Integer id, String rejectReason, String adminName) {
        Integer count = bankerInfoMapper.verifyFail(id, rejectReason, adminName);
        if (count > 0) {
            YxBankerInfo bankerInfo = bankerInfoMapper.selectByPrimaryKey(id);
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(bankerInfo.getBankerId());
            message.setBankerName(bankerInfo.getBankerName());
            message.setRemarks("您上传的商家信息："+bankerInfo.getBankerName()+" 未通过审核,原因:("+rejectReason+")");
            message.setStatus(0);
            message.setType(6);
            message.setCreateTime(new Date());
            bankerMessageMapper.insert(message);
        }
        return count;
    }

    public CommonResult resetPwd(BrandUpdateNameRequest request) {
        Integer num = bankerInfoMapper.resetPwd(request.getId());
        if (num > 0) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }
}
